package com.rc.saas.tenant.controller.ticket;

import com.alibaba.excel.EasyExcel;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.constant.ShiroConstants;
import com.rc.saas.tenant.common.exception.CustomException;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.ImportExcelUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadImg;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.enterprise.RcEnterpriseLevelSetting;
import com.rc.saas.tenant.model.enterprise.RcEnterpriseLevelSettingExample;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.RcMemberLevelSetting;
import com.rc.saas.tenant.model.member.RcMemberLevelSettingExample;
import com.rc.saas.tenant.model.shop.ShopGoods;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.tenant.TenantUserExample;
import com.rc.saas.tenant.model.ticket.TenantTicketSchedule;
import com.rc.saas.tenant.model.ticket.TenantTicketScheduleExample;
import com.rc.saas.tenant.model.ticket.TenantTicketType;
import com.rc.saas.tenant.model.ticket.TenantTicketTypeExample;
import com.rc.saas.tenant.search.member.MemberTicketSearch;
import com.rc.saas.tenant.search.order.OrderRefundApplySearch;
import com.rc.saas.tenant.search.ticket.TicketSearch;
import com.rc.saas.tenant.search.ticket.TicketSendRecordSearch;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.enterprise.RcEnterpriseLevelSettingService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.member.MemeberLevelService;
import com.rc.saas.tenant.service.shop.ShopGoodsService;
import com.rc.saas.tenant.service.shop.ShopGoodsServiceImpl;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.service.ticket.MemberTicketService;
import com.rc.saas.tenant.service.ticket.TenantTicketScheduleService;
import com.rc.saas.tenant.service.ticket.TenantTicketSendRecordService;
import com.rc.saas.tenant.service.ticket.TenantTicketTypeService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.order.OrderRefundApplyVo;
import com.rc.saas.tenant.vo.ticket.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author frog
 * @date 2021/2/25
 */
@Controller
@RequestMapping("/tenantTicketType")
public class TenantTicketTypeController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TenantTicketTypeService tenantTicketTypeService;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Autowired
    private MemberTicketService memberTicketService;

    @Autowired
    private TenantTicketScheduleService tenantTicketScheduleService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private TenantTicketSendRecordService tenantTicketSendRecordService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private UploadImg uploadImg;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private ShopGoodsServiceImpl shopGoodsServiceImpl;

    @Autowired
    private MemeberLevelService memeberLevelService;

    @Autowired
    private RcEnterpriseLevelSettingService enterpriseLevelSettingService;

    /**
     * 跳转优惠券页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String tenantTicketTypePage() {
        return "/templates/ticket/tenantTicketType";
    }

    /**
     * 返回优惠券列表数据
     *
     * @return
     *
     */
    @RequestMapping(value = "/listTenantTicketType", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listTenantTicketType(TicketSearch search) {
        PageInfo<TicketVo> pageInfo = tenantTicketTypeService.listPageTicket(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转新增优惠券页面
     *
     * @return
     */
    @RequestMapping(value = "/addTenantTicketType", method = RequestMethod.GET)
    public String addTenantTicketType(Model model) {

        RcMemberLevelSettingExample example = new RcMemberLevelSettingExample();
        example.createCriteria().andStatusEqualTo("0");
        List<RcMemberLevelSetting> list = memeberLevelService.selectByExample(example);

        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
        for (RcMemberLevelSetting level : list) {
            map.put(level.getMemberLevel(), level.getLevelName());
        }
        model.addAttribute("levelMap", map);

        List<RcEnterpriseLevelSetting> enterLevels = enterpriseLevelSettingService.listLevel();
        model.addAttribute("enterLevels", enterLevels);
        return "/templates/ticket/addTenantTicketType";
    }

    /**
     * 返回优惠券对应桩群
     *
     * @return
     */
    @RequestMapping(value = "/listTicketStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse listTicketStation(Long ticketTypeId) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();
            List<ElecStation> elecStations = elecStationService.listAllStationAndHlht(user.getTenantCode(), ticketTypeId);
            return TResponse.SUCCESS_DATA(elecStations);
        } catch (Exception e) {
            logger.error("查询优惠券对应桩群", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 返回优惠券对应桩群(外部互联互通)
     *
     * @return
     */
    @RequestMapping(value = "/listTicketStationExternalHlht", method = RequestMethod.POST)
    @ResponseBody
    public TResponse listTicketStationExternalHlht(Long ticketTypeId) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();
            Map<String, List<ElecStation>> elecStations = elecStationService.listTicketStationExternalHlht(user.getTenantCode(), ticketTypeId);
            return TResponse.SUCCESS_DATA(elecStations);
        } catch (Exception e) {
            logger.error("查询优惠券对应桩群(外部互联互通)", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 返回优惠券对应桩群(内部互联互通)
     *
     * @return
     */
    @RequestMapping(value = "/listTicketStationHlht", method = RequestMethod.POST)
    @ResponseBody
    public TResponse listTicketStationHlht(Long ticketTypeId) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();
            Map<String, List<ElecStation>> elecStations = elecStationService.listTicketStationHlht(user.getTenantCode(), ticketTypeId);
            return TResponse.SUCCESS_DATA(elecStations);
        } catch (Exception e) {
            logger.error("查询优惠券对应桩群(内部互联互通)", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 保存/编辑优惠券
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateTenantTicketType", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateTenantTicketType(TenantTicketTypeDto tenantTicketTypeDTO, @RequestParam(value = "file", required = false) MultipartFile file) {

        try {
            if (StringUtils.isNotBlank(tenantTicketTypeDTO.getLevels())){
                tenantTicketTypeDTO.setApplicnceLevel(tenantTicketTypeDTO.getLevels());
            }
            if (!BeanUtil.isValid(tenantTicketTypeDTO.getTicketName(),
                    tenantTicketTypeDTO.getUseRequireAmount())) {
                return TResponse.FAIL("请输入正确的参数");
            }
            if (tenantTicketTypeDTO.getStationIds().size() == 0) {
                return TResponse.FAIL("请选择站点限制");
            }

            if ("1".equals(tenantTicketTypeDTO.getIsMax())) {
                tenantTicketTypeDTO.setTotalTicket(100000000);
            }else {
                if (tenantTicketTypeDTO.getTotalTicket() == null) {
                    return TResponse.FAIL("请输入发放总数量");
                }
            }

            TenantUser user = ShiroUtils.getSessionUser();
            if (file != null && file.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file);
                if (tResponse.getStatus() == 200) {
                    tenantTicketTypeDTO.setTicketImg1((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }

            tenantTicketTypeDTO.setTenantCode(user.getTenantCode());
            tenantTicketTypeService.saveOrUpdateTenantTicketType(tenantTicketTypeDTO);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存优惠券失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 跳转优惠券详情页面
     *
     * @return
     */
    @RequestMapping(value = "/detail/{ticketTypeId}", method = RequestMethod.GET)
    public String detail(@PathVariable("ticketTypeId") Long ticketTypeId, Model model) {
        TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(ticketTypeId);
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        model.addAttribute("tenantTicketType", tenantTicketType);
        return "/templates/ticket/detailTenantTicketType";
    }

    /**
     * 跳转发放记录页面
     *
     * @return
     */
    @RequestMapping(value = "/sendRecord/{ticketTypeId}", method = RequestMethod.GET)
    public String sendRecord(@PathVariable("ticketTypeId") Long ticketTypeId, Model model) {
        model.addAttribute("ticketTypeId", ticketTypeId);
        return "/templates/ticket/sendRecord";
    }

    /**
     * 返回发放记录列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageSendRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageSendRecord(TicketSendRecordSearch ticketSendRecordSearch) {
        PageInfo<TicketSendRecordVo> pageInfo = tenantTicketSendRecordService.listPageSendRecord(ticketSendRecordSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转赠送优惠券页面
     *
     * @return
     */
    @RequestMapping(value = "/giveAway/{ticketTypeId}", method = RequestMethod.GET)
    public String giveAway(@PathVariable("ticketTypeId") Long ticketTypeId, Model model) {
        TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(ticketTypeId);
        model.addAttribute("tenantTicketType", tenantTicketType);
        return "/templates/ticket/giveAway";
    }

    /**
     * 跳转定时赠送优惠券页面
     *
     * @return
     */
    @RequestMapping(value = "/timeingGiveAway/{ticketTypeId}", method = RequestMethod.GET)
    public String timeingGiveAway(@PathVariable("ticketTypeId") Long ticketTypeId, Model model) {
        model.addAttribute("ticketTypeId", ticketTypeId);
        return "/templates/ticket/timeingGiveAway";
    }

    /**
     * 保存赠送优惠券
     *
     * @return
     */
    @RequestMapping(value = "/saveGiveAway", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveGiveAway(HttpSession session, GiveTicketDto giveTicketDTO) {

        try {
            if ("0".equals(giveTicketDTO.getSendType())) {
                if (!BeanUtil.isValid(giveTicketDTO.getSendCount())) {
                    return TResponse.FAIL("请输入正确的参数");
                }
            } else {
                if (!BeanUtil.isValid(giveTicketDTO.getTicketScheduleCount(), giveTicketDTO.getSendNum(), giveTicketDTO.getFirstSendTime())) {
                    return TResponse.FAIL("请输入正确的参数");
                }
            }

            TenantUser sessionUser = ShiroUtils.getSessionUser();
            giveTicketDTO.setTenantCode(sessionUser.getTenantCode());


            TenantUser user = ShiroUtils.getSessionUser();

            TenantUserExample example = new TenantUserExample();
            example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
            TenantUser adminUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

            String sessionAttr = ShiroConstants.SESSION_SENDTICKET_TICKET_KEY + adminUser.getMobile();
            String sessionAuthCode = (String) session.getAttribute(sessionAttr);

            if (StringUtils.isBlank(sessionAuthCode)) {
                return TResponse.FAIL("未申请验证码");
            }

            if (!giveTicketDTO.getVerificationCode().equals(sessionAuthCode.substring(0, 6))) {
                return TResponse.FAIL("验证码错误");
            }

            TResponse tResponse = tenantTicketTypeService.saveGiveAway(giveTicketDTO);

            //删除验证码
            //     session.removeAttribute(sessionAttr);
            return tResponse;
        } catch (CustomException e) {
            logger.error("赠送优惠券失败", e);
            return TResponse.FAIL(e.getMessage());
        } catch (Exception e) {
            logger.error("赠送优惠券失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 上传用户excel
     *
     * @return
     */
    @RequestMapping(value = "/uploadMemberMobile", method = RequestMethod.POST)
    @ResponseBody
    public TResponse uploadMemberMobile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        try {
            String filename = file.getOriginalFilename();
            String fileLastName = filename.substring(filename.length() - 3, filename.length());
            if (!"xls".equals(fileLastName) && !"lsx".equals(fileLastName)) {
                return TResponse.FAIL("请上传xls或者xlsx格式的文件");
            }

            Map<String, Object> result = new HashMap<String, Object>();
            List<String> mobiles = new ArrayList<String>();

            //excel文件上传
            String path = request.getSession().getServletContext().getRealPath("/");
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            try {
                if (!file.isEmpty()) {
                    // 这里将上传得到的文件保存指定目录下
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, fileName));
                }

                InputStream in = null;
                List<List<Object>> listob = null;
                in = file.getInputStream();
                listob = new ImportExcelUtil().getBankListByExcel(in, file.getOriginalFilename());
                for (int i = 0; i < listob.size(); i++) {
                    List<Object> lo = listob.get(i);
                    //TODO 根据excel格式获取指定的参数,还可优化:用正则表达式匹配过滤不符合的参数
                    String mobile = String.valueOf(lo.get(0));
                    mobiles.add(mobile);
                }

            } catch (Exception e) {
                //TODO 记录完善的日志和异常处理
                logger.error("batchAddMobiles()失败,原因为:" + e.getMessage(), e);
            } finally {
                //处理完后需删除本地文件
                File file2 = new File(path + File.separator + fileName);
                if (file2.exists()) {
                    file2.delete();
                }
            }
            TenantUser user = ShiroUtils.getSessionUser();
            LinkedList<Long> linkedList = new LinkedList<>();
            int failMobile = 0;
            //添加判断&业务处理
            if (null != mobiles && mobiles.size() > 0) {
                //TODO 业务逻辑处理
                for (String mobile : mobiles) {
                    MemberInfo memberInfo = memberInfoService.selectMemberByMobile(user.getTenantCode(), mobile);
                    if (memberInfo != null) {
                        linkedList.add(memberInfo.getMemberId());
                    } else {
                        failMobile++;
                    }
                }
            }
            return TResponse.SUCCESS_DATA_MESSAGE(linkedList, String.format("已成功导入%d条手机号码,为你删除无效号码%d条", linkedList.size(), failMobile));
        } catch (Exception e) {
            logger.error("上传用户excel失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存定时赠送优惠券
     *
     * @return
     */
    @RequestMapping(value = "/saveTimeingGiveAway", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveTimeingGiveAway(HttpSession session, TenantTicketSchedule tenantTicketSchedule, String verificationCode) {

        try {
            if (!BeanUtil.isValid(tenantTicketSchedule.getTicketTypeId(), tenantTicketSchedule.getTicketScheduleCount(),
                    tenantTicketSchedule.getFirstSendTime(), verificationCode)) {
                return TResponse.FAIL("请输入正确的参数");
            }

            TenantUser user = ShiroUtils.getSessionUser();
            TenantUserExample example = new TenantUserExample();
            example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
            TenantUser adminUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

            String sessionAttr = ShiroConstants.SESSION_SENDTICKET_TICKET_KEY + adminUser.getMobile();

            String sessionAuthCode = (String) session.getAttribute(sessionAttr);

            if (StringUtils.isBlank(sessionAuthCode)) {
                return TResponse.FAIL("未申请验证码");
            }

            if (!verificationCode.equals(sessionAuthCode.substring(0, 6))) {
                return TResponse.FAIL("验证码错误");
            }

            tenantTicketScheduleService.saveTimeingGiveAway(tenantTicketSchedule, user);
            //删除验证码
            //session.removeAttribute(sessionAttr);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存优惠券失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 获取手机短信验证码
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/getTicketAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public TResponse getTicketAuthCode(HttpSession session) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();

            TenantUserExample example = new TenantUserExample();
            example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
            TenantUser adminUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

            Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
            //验证码
            String smscode = uidGenerator.genSmsAuthCode();

            SendSmsResponse sendResult = AliyunSmsUtil.sendSms(adminUser.getMobile(), smscode, AliyunSmsTemplateEnum.SEND_TICKET, tenant.getSmsSign());

            if (sendResult == null) {
                logger.error("短信系统异常");
                return TResponse.FAIL("短信系统异常");
            }

            if ("OK".equals(sendResult.getCode())) {
                // 更新sms表
                tenantSmsService.updateTenantSmsByTenantCode(tenant.getTenantCode(), adminUser.getMobile(), "0", "tenant,getTicketAuthCode:获取验证码 ,进行发送优惠券功能:" + adminUser.getMobile(), "获取验证码 ,进行发送优惠券功能");
            } else {
                logger.error("短信系统异常:" + sendResult.getMessage());
            }

            //将登录验证码保存到会话中
            String sessionAttr = ShiroConstants.SESSION_SENDTICKET_TICKET_KEY + adminUser.getMobile();
            String sessionAuthCode = smscode + System.currentTimeMillis();
            session.setAttribute(sessionAttr, sessionAuthCode);

            logger.error("获取手机短信验证码 mobile:{},sessionAttr:{},sessionAuthCode:{}", adminUser.getMobile(), sessionAttr, sessionAuthCode);

            return TResponse.SUCCESS("验证码已发送");
        } catch (Exception e) {
            logger.error("获取发送优惠券验证码失败", e);
            return TResponse.FAIL("操作失败");
        }


    }


    /**
     * 优惠券的启动和停用
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public TResponse updateStatus(Long ticketTypeId) {
        try {
            TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(ticketTypeId);
            if ("0".equals(tenantTicketType.getStatus())) {
                tenantTicketType.setStatus("1");
                //同时下架所有该优惠券的商品
                List<ShopGoods> list = shopGoodsServiceImpl.listByTicketTypeId(ticketTypeId);
                if(list!=null){
                    for(ShopGoods shopGoods:list){
                        shopGoods.setStatus("10");
                        shopGoods.setLastUpdatedTime(new Date());
                        shopGoodsServiceImpl.updateByPrimaryKeySelective(shopGoods);
                    }
                }
            } else {
                tenantTicketType.setStatus("0");
            }
            tenantTicketTypeService.updateByPrimaryKeySelective(tenantTicketType);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("更新优惠券状态失败", e);
            return TResponse.FAIL("更新优惠券失败");
        }
    }

    /**
     * 跳转发送优惠券详情页面
     *
     * @return
     */
    @RequestMapping(value = "/detialSendRecord/{ticketSendRecordId}", method = RequestMethod.GET)
    public String detialSendRecord(@PathVariable("ticketSendRecordId") Long ticketSendRecordId, Model model) {
        model.addAttribute("ticketSendRecordId", ticketSendRecordId);
        return "/templates/ticket/detialSendRecord";
    }

    /**
     * 返回发送优惠券详情列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageDetialSendRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageDetialSendRecord(MemberTicketSearch memberTicketSearch) {
        PageInfo<MemberTicketResultVo> pageInfo = memberTicketService.listPageDetialSendRecord(memberTicketSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转获取优惠券记录页面
     *
     * @return
     */
    @RequestMapping(value = "/getRecord/{ticketTypeId}", method = RequestMethod.GET)
    public String getRecord(@PathVariable("ticketTypeId") Long ticketTypeId, Model model) {
        model.addAttribute("ticketTypeId", ticketTypeId);
        return "/templates/ticket/getRecord";
    }


    /**
     * 跳转赠送优惠券记录页面
     *
     * @return
     */
    @RequestMapping(value = "/giveRecord/{ticketTypeId}", method = RequestMethod.GET)
    public String giveRecord(@PathVariable("ticketTypeId") Long ticketTypeId, Model model) {
        model.addAttribute("ticketTypeId", ticketTypeId);
        return "/templates/ticket/giveRecord";
    }


    /**
     * 返回获取优惠券列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listGetRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listGetRecord(MemberTicketSearch memberTicketSearch) {
        PageInfo<MemberTicketResultVo> pageInfo = memberTicketService.listPageDetialSendRecord(memberTicketSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 返回赠送优惠券列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listGiveRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listGiveRecord(BaseSearch baseSearch, Long ticketTypeId) {
        TenantTicketScheduleExample example = new TenantTicketScheduleExample();
        example.createCriteria().andTicketTypeIdEqualTo(ticketTypeId);
        List<TenantTicketSchedule> tenantTicketSchedules = tenantTicketScheduleService.selectByExample(example);
        PageHelper.startPage(baseSearch.getOffset(), baseSearch.getLimit());
        PageInfo<TenantTicketSchedule> pageInfo = new PageInfo<>(tenantTicketSchedules);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 删除赠送优惠券记录
     *
     * @return
     */
    @RequestMapping(value = "/deleteGiveRecord", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteGiveRecord(Long ticketTypeId) {
        try {
            tenantTicketScheduleService.deleteByPrimaryKey(ticketTypeId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除赠送优惠券记录失败", e);
            return TResponse.FAIL("删除赠送优惠券记录失败");
        }
    }

    /**
     * 跳转优惠券详情页面
     *
     * @return
     */
    @RequestMapping(value = "/edit/{ticketTypeId}", method = RequestMethod.GET)
    public String edit(@PathVariable("ticketTypeId") Long ticketTypeId, Model model) {
        TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(ticketTypeId);
        RcMemberLevelSettingExample example = new RcMemberLevelSettingExample();
        example.createCriteria().andStatusEqualTo("0");
        List<RcMemberLevelSetting> list = memeberLevelService.selectByExample(example);

        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
        for (RcMemberLevelSetting level : list) {
            map.put(level.getMemberLevel(), level.getLevelName());
        }
        List<RcEnterpriseLevelSetting> enterLevels = enterpriseLevelSettingService.listLevel();
        model.addAttribute("enterLevels", enterLevels);
        model.addAttribute("levelMap", map);
        model.addAttribute("tenantTicketType", tenantTicketType);
        return "/templates/ticket/editTenantTicketType";
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public TResponse delete(Long id) {
        tenantTicketTypeService.deleteByPrimaryKey(id);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/updateTicketForChangeStatus", method = RequestMethod.POST)
    public TResponse updateTicketForChangeStatus(Long id, String status) {
        TenantTicketType ticketType = tenantTicketTypeService.selectByPrimaryKey(id);
        ticketType.setStatus(status);
        tenantTicketTypeService.updateByPrimaryKeySelective(ticketType);
        return TResponse.SUCCESS();
    }
    @ResponseBody
    @RequestMapping(value = "/getAllData", method = RequestMethod.POST)
    public List<TicketVo> getAllData() {
        TenantUser user = ShiroUtils.getSessionUser();
        TicketSearch search = new TicketSearch();
        search.setStatus("0");
        List<TicketVo> ticketVo = tenantTicketTypeService.getTenantTickets(search);
        return ticketVo;
    }

    /**
     * 导出卡劵列表数据
     */
    @ResponseBody
    @RequestMapping("/exporListTenantTicketType")
    public TResponse exporListTenantTicketType(TicketSearch search, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        ExportUtils.setDefaultPaging(search);
        try {
            PageInfo<TicketVo> pageInfo = tenantTicketTypeService.listPageTicket(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("卡券列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TicketVo.class).sheet("卡劵列表").doWrite(pageInfo.getList());
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }



}
